import { Provide, httpError } from '@midwayjs/core'
import { ReturnModelType } from '@typegoose/typegoose'
import { InjectEntityModel } from '@midwayjs/typegoose'
import { randomUUID } from 'node:crypto'
import { Role } from '../entity/role.js'

@Provide()
export class RolesService {
  @InjectEntityModel(Role)
  roleModel: ReturnModelType<typeof Role>

  async insertMany(data): Promise<any> {
    for (const item of data) {
      const roleInfo = await this.roleModel
        .findOne({
          name: item.name
        })
        .exec()
      if (roleInfo) throw new httpError.ForbiddenError('角色已存在')
      else {
        const role: any = item
        if (!role.id) role.id = randomUUID()
      }
    }
    const createdRole = this.roleModel.insertMany(data)
    return createdRole
  }

  async find(): Promise<Role[]> {
    return this.roleModel.find({ name: /^(?!admin)/ }).exec()
  }

  async findOne(data): Promise<Role | null> {
    return this.roleModel.findOne(data).exec()
  }

  async updateOne(data: any) {
    Reflect.deleteProperty(data, '_id')
    return this.roleModel.updateOne({ id: data.id }, { $set: data }).exec()
  }

  async deleteOne(data: any): Promise<any> {
    if (data) {
      const deletedRole = await this.roleModel.deleteOne(data).exec()
      return deletedRole
    }
  }

  async initRoles() {
    const data: any = { name: 'admin' }

    const roleInfo: any = await this.findOne(data)
    if (!roleInfo) {
      return (
        await this.insertMany([
          {
            name: data.name,
            pid: '',
            menus: []
          }
        ])
      )[0]
    } else return roleInfo
  }
}
